package api

import (
	"context"
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	ark "github.com/sashabaranov/go-openai"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"video_demo/config"
	"video_demo/entity"
	"video_demo/result"
)

func saveFile(file multipart.File, path string) error {
	defer file.Close()
	out, err := os.Create(path)
	if err != nil {
		return err
	}
	defer out.Close()
	_, err = io.Copy(out, file)
	return err
}

func Upload(c *gin.Context) {

	// 文件处理部分
	fileHeader, err := c.FormFile("image")
	if err != nil {
		http.Error(c.Writer, "文件解析失败", http.StatusBadRequest)
		return
	}

	file, err := fileHeader.Open()
	if err != nil {
		http.Error(c.Writer, "文件打开失败", http.StatusBadRequest)
		return
	}
	defer file.Close()

	saveDir := "D:\\ShanghaiLixiang\\jpgs"
	if _, err := os.Stat(saveDir); os.IsNotExist(err) {
		if err := os.MkdirAll(saveDir, 0755); err != nil {
			http.Error(c.Writer, "创建保存目录失败", http.StatusInternalServerError)
			return
		}
	}

	filePath := filepath.Join(saveDir, fileHeader.Filename)
	if err := saveFile(file, filePath); err != nil {
		http.Error(c.Writer, "保存文件失败", http.StatusInternalServerError)
		return
	}

	// 读取图片文件内容
	imgData, err := os.ReadFile(filePath)
	if err != nil {
		http.Error(c.Writer, fmt.Sprintf("读取图片文件失败: %v", err), http.StatusInternalServerError)
		return
	}

	// 将图片内容转换为 Base64 编码
	base64Img := base64.StdEncoding.EncodeToString(imgData)

	if _, err := base64.StdEncoding.DecodeString(base64Img); err != nil {
		fmt.Printf("Base64 编码错误: %v\n", err)
	}

	// 调用 OpenAI
	cfg := ark.DefaultConfig(os.Getenv("ARK_API_KEY"))
	cfg.BaseURL = config.SysConfig.AIModel.URL
	client := ark.NewClientWithConfig(cfg)

	req := ark.ChatCompletionRequest{
		Model: config.SysConfig.AIModel.VersionModel,
		Messages: []ark.ChatCompletionMessage{
			{
				Role: ark.ChatMessageRoleUser,
				MultiContent: []ark.ChatMessagePart{
					{
						Type: ark.ChatMessagePartTypeText,
						Text: "批改下面的试卷",
					},
					{
						Type: ark.ChatMessagePartTypeImageURL,
						ImageURL: &ark.ChatMessageImageURL{
							URL: "data:image/jpeg;base64," + base64Img,
						},
					},
				},
			},
		},
	}

	resp, err := client.CreateChatCompletion(context.Background(), req)
	if err != nil {
		http.Error(c.Writer, fmt.Sprintf("ChatCompletion error: %v", err), http.StatusInternalServerError)
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}

	response := &entity.ChatResponse{
		Content: resp.Choices[0].Message.Content,
	}
	c.JSON(http.StatusOK, result.Success("试卷解析成功", response))

}
